<template>
  <div class="cafeteria-events-admin">
    <div class="event-list">
      <h2>活动列表</h2>
      <div class="scroll-container">
        <ul>
          <li class="event-list-header">
            <span class="event-name" >活动名称</span>
            <button @click="toggleDeletedEvents()">
              {{ showingDeletedEvents ? '回到当前活动' : '查看历史活动' }}
            </button>
          </li>

          <li v-for="event in events" :key="event.id" class="event-item">
            <img :src="getImageUrl(event.image_url)" alt="Event image" class="event-image-small"/>
            <span class="event-name">{{ event.title }}</span>
            <div class="event-actions">
              <button v-if="!showingDeletedEvents" @click="signUpEvent(event)">查看报名情况</button>
              <button v-if="!showingDeletedEvents" @click="editEvent(event)">编辑</button>
              <button v-if="!showingDeletedEvents" @click="deleteEvent(event)">删除</button>
              <button v-if="showingDeletedEvents" @click="restoreEvent(event)">恢复</button>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- Event Management - Right Panel -->
    <div class="event-management">

<!--      <div v-if="loading" class="loading">加载中...</div>-->

        <h2>添加新活动</h2>
        <form @submit.prevent="submitEvent">
          <input v-model="form.title" type="text" placeholder="活动标题" />
          <textarea v-model="form.summary" style="  height: 10vh;" placeholder="活动概述"></textarea>
          <textarea v-model="form.detail" placeholder="活动描述"></textarea>
          <input v-model="form.start_date" type="date" placeholder="开始日期" /> <!-- 新增 -->
          <input v-model="form.end_date" type="date" placeholder="结束日期" /> <!-- 新增 -->
          <div class="file-upload-container">
          <a>上传活动图片</a> <input type="file" @change="handleFileUpload" />
            </div>

            <button type="submit">添加</button>
        </form>
    </div>

    <EventEditCard v-if="showEventCard" :event="editableEvent" @save="saveEvent" @close="closeEventCard" />
    <EventSignUpCard v-if="showSignUpCard" :event="showSignUp" @close="closeSignUpCard" />

  </div>
</template>

<script>
import { getCurrentEvents, addNewEvent, updateEvent, getHistoryEvents } from '@/api/events';
import EventEditCard from '../../components/EventEditCard.vue';
import EventSignUpCard from '../../components/EventSignUpCard.vue';


import { baseURL } from '@/utils/request';
import { getAccessToken } from '@/utils/auth';
import { uploadImage } from '@/api/utils'; // Ensure you have this utility if you're handling image uploads

export default {
  name: 'CafeteriaEventsAdmin',
  components: {
    EventEditCard,
    EventSignUpCard
  },
  data() {
    return {
      events: [],
      loading: false,
      showEventCard: false,
      showSignUp: false,
      editableEvent: null,
      showingDeletedEvents: false,
      showSignUpCard: false,

      form: {
        title: '',
        summary: '',
        detail: '',
        imageUrl: '',
        start_date: '',
        end_date: '',
        is_deleted: '',
      },
    };
  },
  methods: {


    getImageUrl(path) {
      return `${baseURL}${path}`;
    },
    toggleDeletedEvents() {
      this.showingDeletedEvents = !this.showingDeletedEvents;
      this.fetchEvents();
    },
    async fetchEvents() {
      const token = getAccessToken();
      if (!token) {
        alert('请登录');
        return;
      }
      this.loading = true;
      try {
        let response;
        if (this.showingDeletedEvents) {
          response = await getHistoryEvents();
        } else {
          response = await getCurrentEvents();
        }
        this.events = response.data;
      } catch (error) {
        console.error('Error fetching events:', error);
      } finally {
        this.loading = false;
      }
    },
    addNewEvent() {
      this.showEventCard = false;
      this.editableEvent = null;
    },
    editEvent(event) {
      this.editableEvent = { ...event };
      this.showEventCard = true;
    },
    signUpEvent(event) {
      this.showSignUp = { ...event };
      this.showSignUpCard = true;
    },
    closeEventCard() {
      this.showEventCard = false;
      this.editableEvent = null;
    },
    async saveEvent(eventData) {
      this.loading = true;
      try {
        if (this.editableEvent && this.editableEvent.id) {
          await updateEvent(this.editableEvent.id, eventData);
        } else {
          await addNewEvent(eventData);
        }
        this.fetchEvents();
      } catch (error) {
        console.error('Error saving event:', error);
      } finally {
        this.loading = false;
        this.closeEventCard();
      }
    },
    async deleteEvent(event) {
      const confirmation = confirm('确定要删除这个活动吗？');
      if (!confirmation) {
        return;
      }
      this.loading = true;
      try {
        console.log('111TTTEEST'+ event)

        event.is_deleted = '1';
        console.log('2222TTEEST'+ event)

        await updateEvent(event.eventId, event);
        await this.fetchEvents(); // 删除后重新加载数据
      } catch (error) {
        console.error('Error deleting event:', error);
      } finally {
        this.loading = false;
      }
    },

    async restoreEvent(event) {
      try {
        event.is_deleted = '0'; // 设置is_deleted为0表示恢复活动
        await updateEvent(event.id, event);
        await this.fetchEvents(); // 恢复后重新加载数据
      } catch (error) {
        console.error('Error restoring event:', error);
      }
    },

    async handleFileUpload(event) {
      this.selectedFile = event.target.files[0];
      try {
        const formData = new FormData();
        formData.append('file', this.selectedFile);

        // 获取前端上传的文件名
        const fileName = this.selectedFile.name;

        // 执行上传操作
        await uploadImage(formData);

        // 拼接路径前缀和图片名
        this.form.imageUrl = `/images/events/${fileName}`;

      } catch (error) {
        console.error(error);
      }
    },

    closeSignUpCard() {
      this.showSignUpCard = false;
    },

    async submitEvent() {
      const eventData = {
        title: this.form.title,
        summary: this.form.summary,
        detail: this.form.detail,
        image_url: this.form.imageUrl,
        start_date: this.form.start_date,
        end_date: this.form.end_date,
        // is_deleted: this.form.is_deleted,

    };

      try {
        console.log(eventData);
        let response;
        if (this.editableEvent) {
          response = await updateEvent(this.editableEvent.id, eventData);
        } else {
          response = await addNewEvent(eventData);
        }

        // Check for success response
        if (response && response.data) {
          alert(response.data.message || '活动添加成功');
        } else {
          alert('Event submission failed');
        }

        this.resetForm();
        await this.fetchEvents();
      } catch (error) {
        // Handle errors
        if (error.response && error.response.data) {
          alert(error.response.data.message || '活动添加失败');
        } else {
          alert('活动添加失败');
        }
        console.error('Error during event submission', error);
      }
    },
    resetForm() {
      this.form = { title: '', detail: '', summary: '', imageUrl: '' };
    },
  },
  mounted() {
    this.fetchEvents();
  }
};
</script>

<style scoped>
.cafeteria-events-admin {
  display: flex;
  gap: 20px;
  margin: 0 auto;
  max-width: 1200px;
  height: 85vh;
  padding: 20px;
  font-family: 'Arial', sans-serif; /* Consistent font family */
}

.event-list {
  flex: 1;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;

}

.scroll-container {
  max-height: 72vh;
  overflow-y: auto;
  margin-right: -7px;
  padding-right: 7px;
}

.event-list ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.event-list .event-item {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  padding: 1px;
}

.event-list .event-item .event-image-small {
  width: 80px; /* Adjust size as needed */
  height: 80px; /* Adjust size as needed */
  border-radius: 20px;
  object-fit: cover;
  margin-right: 10px;
}

.event-list .event-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.event-list .event-name {
  font-weight: bold;
  color: #333;
}

.event-management {
  flex: 1;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.loading {
  text-align: center;
  padding: 50px 0;
  font-size: 1.2em;
  color: #666;
}

.cafeteria-events-admin button {
  background-color: #93bdd8;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin-top: 5px;
  margin-bottom: 5px;
  padding: 5px;
}

.cafeteria-events-admin button:hover {
  background-color: #A4D3F1;
}


.event-management input[type="text"] {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}


.event-management textarea {
  width: 100%;
  height: 20vh;

  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}
.event-management button[type="submit"] {
  width: 100%;
  background-color: #93bdd8;
  color: white;
  padding: 14px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
}

.event-management button[type="submit"]:hover {
  background-color: #A4D3F1;
}

input[type="file"] {
  margin-top: 15px;
  font-size: 14px;
}

.event-list-header {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 100;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 4px;

  margin-bottom: 5px;
  padding:1px;

}


.event-list .event-item .event-actions, .event-list-header button {
  margin-right: 4px;
}

.event-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.event-list-header .event-name {
  margin-left: 150px; /* 活动名称距离左边框20% */
}

.event-list-header button {
  margin-right: 5px; /* 查看历史活动按钮距离右边框10% */
}

.file-upload-container {
  display: block;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  width: 100%; /* 设置为父容器的宽度 */
}

.file-upload-container a {
  display: inline-block; /* 将 <a> 元素设置为内联块级元素 */
  /* 其他需要的样式 */
}


</style>
